package com.hongtech.tiny.modules.sys.service.impl;

import com.hongtech.tiny.common.exception.CustomException;
import com.hongtech.tiny.common.service.RedisService;
import com.hongtech.tiny.modules.sys.service.SysCaptchaService;
import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.base.Captcha;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * 验证码
 */
@Service
@RequiredArgsConstructor
public class SysCaptchaServiceImpl implements SysCaptchaService {

    private final RedisService redisService;

    @Value("${redis.database}")
    private String redisDatabase;

    @Value("${redis.key.captcha}")
    private String redisKeyCaptcha;

    /**
     * 生成验证码
     *
     * @param uuid 唯一标识码
     */
    @Override
    public String getCaptcha(String uuid) {
        if (StringUtils.isBlank(uuid)) {
            throw new CustomException("uuid不能为空");
        }
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(120, 40);
        captcha.setCharType(Captcha.TYPE_DEFAULT);
        String text = captcha.text();
        // 验证码存储redis 设置过期时间
        String key = redisDatabase + ":" + redisKeyCaptcha + ":" + uuid;
        redisService.set(key, text, 5 * 60L);
        return captcha.toBase64();
    }

    /**
     * 验证验证码是否有效
     *
     * @param uuid 唯一标识码
     * @param code 验证码
     */
    @Override
    public boolean validate(String uuid, String code) {
        String key = redisDatabase + ":" + redisKeyCaptcha + ":" + uuid;
        String codeObject = (String) redisService.get(key);
        if (StringUtils.isEmpty(codeObject)) {
            return false;
        }
        if (codeObject.equals(code)) {
            redisService.del(key);
            return true;
        }
        return false;
    }

}
